package com.llkj.youdaocar;

import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import com.llkj.youdaocar.httpUtils.HttpMethod;
import com.llkj.youdaocar.utils.MediaUtility;
import com.llkj.youdaocar.utils.Utils;
import com.truckmaster.driver.sharesdk.ShareUtils;
import com.truckmaster.driver.sharesdk.ToastUtil;

import java.io.File;
import butterknife.BindView;

import static com.llkj.youdaocar.LoginActivity.USER_ID;

public class MainActivity extends BaseActivity {

    public static final int REQUEST_LOGIN_CODE = 9980;
    private final String SHARE_TITLE = "友道汽车app下载";
    private final String SHARE_CONTENT = "友道汽车是一款为汽车消费者精心打造的购车助手软件，帮助消费者以更优惠的价格选到心仪的爱车，早日成为有车一族。";
    private final String SHARE_IMAGE_PATH = "http://101.200.63.2:8080/file-server/share/shareimg.png";

    @BindView(R.id.webView)
    WebView webView;
    @BindView(R.id.progressBar)
    ProgressBar progressBar;
//    @BindView(R.id.statusView)
//    StatusView mStatusView;
    private WebSettings settings;
    private String url = HttpMethod.HOME_INDEX;
    private String title = "";
    private String webViewTitle = "";
    private String mCurrentUrl,linkUrl;
    private String userId;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        progressBar.setVisibility(View.GONE);
        webView.loadUrl(url);

        userId = MyApplication.getInstance().getSpUtil().getString(USER_ID);
        if(!TextUtils.isEmpty(userId)){
            loadJsMethod();
        }
        if(intent.hasExtra("url")){
            linkUrl = intent.getStringExtra("url");
            if(!TextUtils.isEmpty(linkUrl)){
                initAnim(linkUrl);
            }
        }

    }

    private void  initAnim(final String linkUrl) {
        ValueAnimator objectAnimator = ValueAnimator.ofInt(0,2000);
        objectAnimator.setDuration(2000);
        objectAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                int value = (int) valueAnimator.getAnimatedValue();
                if(value==2000){
                    Intent intent = new Intent(MainActivity.this,WebViewActivity.class);
                    intent.putExtra("url",linkUrl);
                    startActivity(intent);
                }
            }
        });
        objectAnimator.start();

    };

    @Override
    protected void onPause() {
        super.onPause();
//		webView.onPause();
//		webView.pauseTimers();
    }

    @Override
    public void onResume() {
        super.onResume();
        webView.onResume();
        webView.resumeTimers();
    }

    protected void initView() {
        settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        // 设置允许JS弹窗
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setAllowFileAccess(true);
        settings.setDatabaseEnabled(true);
        //webview定位相关设置
        settings.setGeolocationEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setSaveFormData(false);
        settings.setAppCacheEnabled(false);
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        settings.setLoadWithOverviewMode(true);
        settings.setUseWideViewPort(true);
        webView.setWebChromeClient(new MywebChromeClient());
        webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        webView.setWebViewClient(new MyWebClicne());
        //在js中调用本地java方法
        webView.addJavascriptInterface(new JsInterface(this), "appdowhat");

    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK){
            if(requestCode==REQUEST_LOGIN_CODE){
                userId = data.getStringExtra("uid");
                webView.loadUrl(url);
                loadJsMethod();
            }
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//处理h5调用本地相册
            if (requestCode == REQUEST_SELECT_FILE) {
                if (uploadMessage == null)
                    return;
                uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
                uploadMessage = null;
            }
        } else if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage)
                return;
            // Use MainActivity.RESULT_OK if you're implementing WebView inside Fragment
            // Use RESULT_OK only if you're implementing WebView inside an Activity
            Uri result = data == null ? null : data.getData();
            if (result != null) {
                String path = MediaUtility.getPath(getApplicationContext(),
                        result);
                Uri uri = Uri.fromFile(new File(path));
                mUploadMessage.onReceiveValue(uri);
            } else {
                mUploadMessage.onReceiveValue(null);
            }
            mUploadMessage = null;
        }
    }

    private void loadJsMethod(){
          if(!TextUtils.isEmpty(userId)){
                final String urls = "javascript:storagebtn("+userId+")";
//            if(Build.VERSION.SDK_INT<18){
                webView.post(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("Log","=====loadJsMethod()======");
                        webView.loadUrl(urls);
                    }
                });
//            }else{
//                webView.evaluateJavascript(urls, new ValueCallback<String>() {
//                    @Override
//                    public void onReceiveValue(String value) {
//                        //此处为 js 返回的结果
//                    }
//                });
//            }
            }
    }

    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void onLowMemory() {
        Log.e("Log", "=====onLowMemory()====");
        super.onLowMemory();
    }

    @Override
    protected void onDestroy() {
        Log.e("Log", "=====onDestroy()====");
        if (webView != null) {
            webView.clearHistory();
            webView.clearSslPreferences();
            webView.clearFormData();
            webView.clearCache(true);
            webView.clearView();
            ((ViewGroup) webView.getParent()).removeView(webView);
            webView.destroy();
            webView = null;
        }
        super.onDestroy();
    }

    private class JsInterface {
        private Context mContext;

        public JsInterface(Context context) {
            this.mContext = context;
        }
        //在js中调用window.AndroidWebView.xxx(name)，便会触发此方法。
        @JavascriptInterface
        public void gologin() {
            Log.e("Log", "=====gologin()=====");
            Intent intent = new Intent(MainActivity.this,LoginActivity.class);
            startActivityForResult(intent,REQUEST_LOGIN_CODE);
        }

        @JavascriptInterface
        public void ginseng(String ginseng) {
            Log.e("Log", "=====状态栏颜色状态ginseng()====="+ginseng);
            try {
                if("1".equals(ginseng)){
                    setStatus(R.color.white,true);
                }else{
                    setStatus(R.color.gray,false);
                }
            }catch (Exception e){}

        }

        @JavascriptInterface
        public void gess(String value) {//点击
            ginseng(value);
        }

        @JavascriptInterface
        public void tofshare(String url) {//朋友圈分享
            ShareUtils.shareWithWechatMomentsLink(MainActivity.this,SHARE_TITLE,SHARE_CONTENT,SHARE_IMAGE_PATH,url,null);
        }

        @JavascriptInterface
        public void towshare(String url) {//微信好友分享
            ShareUtils.shareWithWechatLink(MainActivity.this,SHARE_TITLE,SHARE_CONTENT,SHARE_IMAGE_PATH,url,null);
        }

        @JavascriptInterface
        public void toqshare(String url) {//qq分享
            ShareUtils.shareWithQQLink(MainActivity.this,SHARE_TITLE,SHARE_CONTENT,SHARE_IMAGE_PATH,url,null);
        }

        @JavascriptInterface
        public void tologout() {
            MyApplication.getInstance().getSpUtil().put(USER_ID,"");
            Intent intent = new Intent(MainActivity.this,MainActivity.class);
            startActivity(intent);
//            Platform qq = ShareSDK.getPlatform(QQ.NAME);
//            if (qq.isAuthValid()) {
//                qq.removeAccount(true);//执行此操作就可以移除掉本地授权状态和授权信息
//            }
//            Platform wechat = ShareSDK.getPlatform(Wechat.NAME);
//            if (wechat.isAuthValid()) {
//                wechat.removeAccount(true);//执行此操作就可以移除掉本地授权状态和授权信息
//            }
            finish();
        }
    }

    private void setStatus(int color,boolean barDark){
        if(barDark){
            systemBarTintManager.setStatusBarTintColor(ContextCompat.getColor(this,color));
        }else{
            systemBarTintManager.setStatusBarTintColor(ContextCompat.getColor(this,color));
        }
        systemBarTintManager = Utils.setStatusBarFontColor(this, barDark);
    }

    class MyWebClicne extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.e("Log", "======shouldOverrideUrlLoading=======" + mPermission);
            if (url.startsWith("http:") || url.startsWith("https:")) {
                mCurrentUrl = url;
                Log.e("Log","=====mCurrentUrl======"+mCurrentUrl);
                view.loadUrl(mCurrentUrl);
                return true;
            }

			// Otherwise allow the OS to handle things like tel, mailto, etc.
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(intent);
            return true;
        }

        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public void onPageFinished(WebView view, String url) {
            Log.e("Log","======mPermission===="+mPermission);
            progressBar.setVisibility(View.GONE);
            webViewTitle = view.getTitle();
            loadJsMethod();
            view.loadUrl("javascript:(function(){ var status;" +
                    "if(document.getElementById('ginseng')===null){" +
                    "status=2;" +
                    "window.appdowhat.ginseng(status);" +
                    "}else{" +
                    "status = document.getElementById('ginseng').value;" +
                    "}" +
                    "}())");
        }

        @Override
        public void onReceivedError(WebView view, int errorCode,
                                    String description, String failingUrl) {
            progressBar.setVisibility(View.GONE);
        }
        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error){
            handler.proceed();//接受证书
        }
    }

    class MywebChromeClient extends WebChromeClient {
//        @Override
//        public boolean onJsAlert(WebView view, String url, String message,
//                                 final JsResult result) {
//            // 弹窗处理
//            AlertDialog.Builder b2 = new AlertDialog.Builder(MainActivity.this)
//                    .setTitle(R.string.app_name).setMessage(message)
//                    .setPositiveButton("ok", new AlertDialog.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            result.confirm();
//                        }
//                    });
//            b2.setCancelable(false);
//            b2.create();
//            b2.show();
//            return true;
//        }

        @Override
        public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
            Log.e("Log", "=====onGeolocationPermissionsShowPrompt========" + mPermission);
            callback.invoke(origin, true, false);
            super.onGeolocationPermissionsShowPrompt(origin, callback);
        }

        //The undocumented magic method override
        //Eclipse will swear at you if you try to put @Override here
        // For Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");
            MainActivity.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
        }

        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            openFileChooser(uploadMsg);
        }

        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            openFileChooser(uploadMsg);
        }

        // For Lollipop 5.0+ Devices
        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
            if (uploadMessage != null) {
                uploadMessage.onReceiveValue(null);
                uploadMessage = null;
            }

            uploadMessage = filePathCallback;

            Intent intent = fileChooserParams.createIntent();
            try {
                startActivityForResult(intent, REQUEST_SELECT_FILE);
            } catch (ActivityNotFoundException e) {
                uploadMessage = null;
                return false;
            }

            return true;
        }
    }

    private ValueCallback<Uri> mUploadMessage;
    public ValueCallback<Uri[]> uploadMessage;
    public static final int REQUEST_SELECT_FILE = 100;
    private final static int FILECHOOSER_RESULTCODE = 1;
}
